/*	qspi.c 
 *  Arizona State University
 *  CSE 325: Embedded Systems Programming
 *  Lab 5: Game of life
 *  Georgii Tkachuk, Brentton Garber
 *   Emails: 	gtkachuk@asu.edu btgarber@asu.edu
 * 	Description: QSPI module initiation and transfer configuration. QSPI is set to transfer 8 bits per transfer @ 5MHz Frequency
 * 
 */

#include "common.h"

// Initialize the qspi
void qspi_init()
{
	// Configure Port SQ
	MCF_GPIO_PQSPAR |= 1 << 0;								// set pin 0 to the primary (QSPI) function
	MCF_GPIO_PQSPAR |= 1 << 2;								// set pin 1 to the primary (QSPI) function
	MCF_GPIO_PQSPAR |= 1 << 4;								// set pin 2 to the primary (QSPI) function
	
	// Configure QMR
	MCF_QSPI_QMR |= MCF_QSPI_QMR_MSTR;						// User QMR with Master
	MCF_QSPI_QMR &= ~MCF_QSPI_QMR_BITS(31);					// Clear all bits from QMR
	MCF_QSPI_QMR |= MCF_QSPI_QMR_BITS(8);					// Set our transfer size to 8 bits
	MCF_QSPI_QMR &= ~(MCF_QSPI_QMR_CPOL);					// Set CPOL to 0
	MCF_QSPI_QMR &= ~(MCF_QSPI_QMR_CPHA);					// Set CPHA to 0
	
	// Configure our Baud for QMR
	MCF_QSPI_QMR &= ~MCF_QSPI_QMR_BAUD(511);				// Clear the Baud Register
	MCF_QSPI_QMR |= MCF_QSPI_QMR_BAUD( 80000/(2*5000) );	// Set Baud rate to 5 MHz
	
	// Configure QDLYR
	MCF_QSPI_QDLYR &= ~(MCF_QSPI_QDLYR_SPE);				// Clear SPE
	MCF_QSPI_QDLYR &= ~MCF_QSPI_QDLYR_QCD(255);				// Clear QCD
	
	
	// Configure QIR
	MCF_QSPI_QWR &= ~(0xFF0F);								// Clear appropriate pins
	
	// Configure QIR
	MCF_QSPI_QIR &= ~(MCF_QSPI_QIR_WCEFB);					// Clear WCEFB
	MCF_QSPI_QIR &= ~(MCF_QSPI_QIR_ABRTB);					// Clear ABRTB
	MCF_QSPI_QIR &= ~(MCF_QSPI_QIR_ABRTL);					// Clear ABRTL
	MCF_QSPI_QIR &= ~(MCF_QSPI_QIR_WCEFE);					// Clear WCEFE
	MCF_QSPI_QIR &= ~(MCF_QSPI_QIR_ABRTE);					// Clear ABRTE
	MCF_QSPI_QIR &= ~(MCF_QSPI_QIR_SPIFE);					// Clear SPIFE
	MCF_QSPI_QIR |= MCF_QSPI_QIR_WCEF;						// Set WCEF
	MCF_QSPI_QIR |= MCF_QSPI_QIR_ABRT;						// Set ABRT
	MCF_QSPI_QIR |= MCF_QSPI_QIR_SPIF;						// Set SPIF
}

// Transfer a data packet wit the qspi
void qspi_transfer(uint8 data[])
{
	int i;
	
	// Transmit our data packet in bytes. In order of RED, Green, then Row
	for(i=0; i<3; i++)
	{
		MCF_QSPI_QAR = (unsigned short) i;
		MCF_QSPI_QDR = (unsigned short) data[i];
		MCF_QSPI_QAR = (unsigned short) (0x20 + i);
		MCF_QSPI_QDR = (unsigned short) 0x4000;
	}
	
	MCF_QSPI_QWR &= ~(MCF_QSPI_QWR_NEWQP(15));				// Clear NEWQP
	MCF_QSPI_QWR &= ~(MCF_QSPI_QWR_ENDQP(15));				// Clear ENDQP
	MCF_QSPI_QWR |= MCF_QSPI_QWR_ENDQP(2);					// Set bit 1 
	
	// Initialize transfer
	MCF_QSPI_QDLYR |= MCF_QSPI_QDLYR_SPE;
	
	// Wait for qir_spif to not be 0
	while(!MCF_QSPI_QIR & MCF_QSPI_QIR_SPIF) {}
	
	// Clear the transfer complete flag
	MCF_QSPI_QIR |= MCF_QSPI_QIR_SPIF;
}



